﻿using System;
using ProjectDanmaku.Entity.SubLayer.EnemyBullet;
using UnityEditor;
using UnityEngine;
using Random = System.Random;

namespace Editor.ProjectDanmaku.Inspector
{
    [CustomEditor(typeof(TestBulletLayer))]
    public class TestBulletLayerInspector : UnityEditor.Editor
    {
        private Random _random = new Random();
        private int _onceCount = 1;

        private bool _playState;
        private float _time;
        private TestBulletLayer _targetLayer;

        private int _rotateSpeed = 1;

        private void OnEnable()
        {
            EditorApplication.update += Update;
        }

        private void OnDisable()
        {
            EditorApplication.update -= Update;
            _targetLayer = null;
        }

        private void Update()
        {
            if (_playState)
            {
                _time += Time.deltaTime;

                for (int i = 0; i < _onceCount; i++)
                {
                    AddEntityRandomly(
                        /*new Vector2(
                            Mathf.Cos(_time * (1 + _rotateSpeed / 10f)), 
                            Mathf.Sin(_time * (1 + _rotateSpeed / 10f)))*/);
                }
            }
        }

        private void AddEntityRandomly()
        {
            AddEntityRandomly(new Vector2(_random.Next(-100, 100), _random.Next(-100, 100)).normalized);
        }

        private void AddEntityRandomly(Vector2 vec)
        {
            var vDotU = Vector2.Dot(vec, Vector2.up);
            var right = Mathf.Sign(Vector2.Dot(vec, Vector2.right));

            var rad = right * Mathf.Acos(vDotU) + Mathf.PI / 2f;
            
            _targetLayer.AddEntity(new TestBulletData()
            {
                Velocity = vec,
                RotateZ = rad
            });
        }
        
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            var layer = (TestBulletLayer) target;
            _targetLayer = layer;
            
            GUILayout.Space(10);

            if (!Application.isPlaying)
            {
                GUILayout.Label("Console only available in play mode", 
                    new GUIStyle("Label") { fontStyle = FontStyle.Bold });
                return;
            }
            
            GUILayout.Label("Console", new GUIStyle("Label") { fontStyle = FontStyle.Bold });
            
            _onceCount = EditorGUILayout.IntSlider("Once Count", _onceCount, 1, 100);
            _rotateSpeed = EditorGUILayout.IntSlider("Rotate Speed", _rotateSpeed, 1, 150);
            
            if (GUILayout.Button("Emit Randomly"))
            {
                for (int i = 0; i < _onceCount; i++)
                    AddEntityRandomly();
            }
            
            _playState = EditorGUILayout.Toggle("Play", _playState);
            
            GUILayout.Label("Entity Count: " + layer.Entities.Count);
        }
    }
}